<template>
  <q-input
    v-model="searchVal"
    filled
    type="text"
    dense
    debounce="200"
    placeholder="搜索内容"
    @keyup.enter="searchFn"
  >
    <template v-slot:append>
      <q-btn flat round icon="search" @click="searchFn" />
    </template>

    <q-menu no-focus fit max-height="400px" auto-close>
      <q-list dense>
        <q-item>
          <q-item-section class="text-bold">搜索记录 </q-item-section>
          <q-item-section side>
            <q-btn
              dense
              size="sm"
              round
              flat
              color="red"
              icon="close"
              @click.stop="
                () => {
                  webStore.clearSearch();
                  searchList = [];
                }
              "
            >
              <q-tooltip> 清除全部 </q-tooltip>
            </q-btn>
          </q-item-section>
        </q-item>
        <q-item
          clickable
          v-close-popup
          v-for="(item, index) in searchList"
          :key="item"
          @click="
            () => {
              searchVal = item;
              searchFn();
            }
          "
        >
          <q-item-section>{{ item }}</q-item-section>
          <q-item-section side>
            <q-btn
              dense
              size="sm"
              round
              flat
              color="red"
              icon="close"
              @click.stop="
                () => {
                  webStore.searchList.splice(index, 1);
                }
              "
            >
              <q-tooltip> 删除 </q-tooltip>
            </q-btn>
          </q-item-section>
        </q-item>
      </q-list>
    </q-menu>
  </q-input>
</template>

<script setup lang="ts">
import { useWebStore } from 'src/stores/webStore';
import { useYuan } from 'src/use';
import { ref, watch } from 'vue';
import { useRouter } from 'vue-router';

const webStore = useWebStore();

const { push } = useRouter();
const { Warn } = useYuan();
const searchVal = ref('');

const searchList = ref(webStore.searchList);

watch(searchVal, (val) => {
  if (val) {
    searchList.value = webStore.searchList.filter((i) => i.indexOf(val) != -1);
  } else {
    searchList.value = webStore.searchList;
  }
});

const searchFn = () => {
  if (searchVal.value) {
    webStore.addSearch(searchVal.value as string);
    push({
      path: '/search',
      query: { text: searchVal.value },
    }).then(() => {
      searchVal.value = '';
    });
  } else {
    Warn('搜索内容不可为空');
  }
};
</script>

<style scoped></style>
